package com.boyicloud.exchangeconsole.controller

import com.boyicloud.exchangeconsole.domain.ClientInfo
import com.boyicloud.exchangeconsole.viewmodel.IndexViewModel
import de.felixroske.jfxsupport.FXMLController
import de.felixroske.jfxsupport.GUIState
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.*
import javafx.scene.input.MouseButton
import javafx.scene.layout.AnchorPane
import javafx.scene.layout.HBox
import javafx.util.Callback
import jfxtras.styles.jmetro.JMetro
import org.springframework.beans.factory.annotation.Autowired
import java.net.URL
import java.util.*

@FXMLController
class IndexViewController : Initializable {

    @FXML
    lateinit var root: AnchorPane

    @FXML
    lateinit var infoTable: TableView<ClientInfo>

    @Autowired
    lateinit var indexViewModel: IndexViewModel

    @FXML
    lateinit var refreshBtn: Button

    @FXML
    lateinit var rtxBytes: TableColumn<ClientInfo, HBox>

    override fun initialize(location: URL?, resources: ResourceBundle?) {
        val jMetro = JMetro()
        jMetro.parent = root
        refreshBtn.graphicProperty().bindBidirectional(indexViewModel.loading)

        rtxBytes.cellFactory = Callback {
            object : TableCell<ClientInfo?, HBox?>() {
                override fun updateItem(item: HBox?, empty: Boolean) {
                    super.updateItem(item, empty)
                    graphic = if (empty) null else HBox().apply {
                        val curRow = indexViewModel.equipmentList[index]
                        val rx = Label(String.format("收：%.3f MB", curRow.rxBytes))
                        val tx = Label(String.format("发：%.3f MB", curRow.txBytes))
                        spacing = 10.0
                        children.addAll(rx, tx)
                    }
                }
            }
        }

        with(infoTable) {
            items = indexViewModel.equipmentList
            selectionModel.selectedItemProperty().addListener { _, _, newValue ->
                indexViewModel.selectModel.value = newValue
            }
            indexViewModel.buildContextMenu()
            indexViewModel.refresh()
            setOnMouseClicked {
                if (it.button == MouseButton.SECONDARY) {
                    indexViewModel.contextMenu.show(infoTable, it.screenX, it.screenY)
                } else if (it.button == MouseButton.PRIMARY) {
                    indexViewModel.contextMenu.hide()
                }
            }
        }

        GUIState.getStage().setOnCloseRequest {
            indexViewModel.destroy()
        }
    }

    fun onRefresh() {
        indexViewModel.refresh()
    }

    fun onReset() {
        indexViewModel.reset()
    }
}
